//
//  BusinessViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/8.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "CaseDetailViewController.h"
#import "RDVTabBarController.h"
#import "RDVTabBarItem.h"
#import "ServiceView.h"
#import "peisongCell.h"
#import "HttpRequest.h"
#import "UIButton+WebCache.h"
#import "HAODEsingleton.h"
#import "ProductView.h"
#import "MapViewControllers.h"
#import <MapKit/MapKit.h>
#import "ACETelPrompt.h"
#import "UMSocial.h"
#import "BusinessCaseItemListViewController.h"
#import "editCaseViewController.h"
@interface CaseDetailViewController ()<CLLocationManagerDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate,UMSocialUIDelegate>
@property (nonatomic, unsafe_unretained) NSInteger currentIndex;
@property(nonatomic ,strong)NSDictionary*myDic;
@property(nonatomic,strong)   NSString*shuoming;
@property(nonatomic,strong)   NSString*shareUrl;
@end

@implementation CaseDetailViewController
{
    HAODEsingleton *commdity;
    ServiceView *mainScorllView;
    UIScrollView*mainScroll;
    UIScrollView*mainScroll1;
    NSMutableArray*LinkType;
    NSMutableArray*LinkCode;
    NSMutableArray*ImageUrl1;
    UIButton*guanzhuBtn;
    UIView*view;
    NSMutableArray*imagearrays;
    NSMutableArray*imageUrlarrays;
    UIScrollView*scroll2;
    NSArray *active;
    UIView*fengxiangview;
    UIButton* quxiao;
    UIScrollView*fengxiangScroll;
      NSDictionary*dataDicts;

}
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    
    
    
    self.navigationController.delegate = nil;
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden=NO;
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
       UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    if ([commdity.gengxinxiangqing isEqualToString:@""]) {
        [self setup];
    }else{
        
        
        
    }
    
    
}

-(void)editor:(UIButton*)sender{
    commdity.gengxinxiangqing=@"123";
    editCaseViewController *detailViewController = [[editCaseViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    commdity=[HAODEsingleton shared];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    
    
    
    
    
    UIButton*editor = [[UIButton alloc] initWithFrame:CGRectMake(0, 0.0, 26, 26)];
    [editor setImage:[UIImage imageNamed:@"fenxiangss"] forState:UIControlStateNormal];
    [editor addTarget:self action:@selector(fenxiangss:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton*editor1 = [[UIButton alloc] initWithFrame:CGRectMake(30, 0.0, 30, 30)];
    [editor1 setImage:[UIImage imageNamed:@"bianji-bai"] forState:UIControlStateNormal];
    [editor1 addTarget:self action:@selector(editor:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:editor];
    UIBarButtonItem* myBtnBtn1 = [[UIBarButtonItem alloc] initWithCustomView:editor1];
    
    NSArray *buttonArray = [[NSArray alloc]initWithObjects:myBtnBtn1,myBtnBtn, nil];
    self.navigationItem.rightBarButtonItems = buttonArray;
    
    
    commdity =[HAODEsingleton shared];
    
    self.view.backgroundColor=[UIColor blackColor];
    
}

-(void)setup{
    [mainScroll removeFromSuperview];
    [scroll2 removeFromSuperview];
    imagearrays=[[NSMutableArray alloc]init];
    
    imageUrlarrays=[[NSMutableArray alloc]init];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    
    [param setValue:commdity.caseID forKey:@"caseID"];
    //[param setValue:self.sats forKey:@"orderField"];
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"/Business/Case/Detail" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                
                scroll2 = [[UIScrollView alloc]initWithFrame:CGRectMake(0, ScreenHeight*280/1334, ScreenWidth, ScreenHeight*750/1334)];
                scroll2.userInteractionEnabled = YES;
                scroll2.scrollEnabled = YES;
                scroll2.showsVerticalScrollIndicator = FALSE;
                scroll2.showsHorizontalScrollIndicator = FALSE;
                
                scroll2.delegate=self;
                [self.view addSubview:scroll2];
                
                
                dataDicts=severDataDict.dataDict;
                commdity.Dict=severDataDict.dataDict;
                
                
               

                commdity.content=[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"type"]];
                commdity.caseStylecontent=[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"caseStyle"]];
                commdity.caseHousecontent=[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"caseHouse"]];
                
                commdity.code=[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"typeCode"]];
                commdity.caseHouseCode=[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"caseHouseCode"]];
                commdity.caseStyleCode=[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"caseStyleCode"]];
                
                
                active = [severDataDict.dataDict objectForKey:@"imageList"];
                if (active.count>0) {
                    scroll2.contentSize = CGSizeMake(ScreenWidth * active.count, 0);
                    for (int i = 0; i < active.count; i++) {
                        
                        UIButton*image=[[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth*i,0, ScreenWidth, ScreenHeight*750/1334)];
                        [image setImageWithURL:[NSURL URLWithString:[[active objectAtIndex:i] objectForKey:@"imageUrlFull"]] placeholderImage:nil];
                        [image setContentMode:UIViewContentModeScaleAspectFill];
                        [scroll2 addSubview:image];
                        
                        [self getImageFromURL:[[active objectAtIndex:i] objectForKey:@"imageUrlFull"]];
                        [self getImageFromURLs:[[active objectAtIndex:i] objectForKey:@"imageUrl"]];

                        if (i == active.count - 1) {
                            
                            UIButton * next = [UIButton buttonWithType:UIButtonTypeCustom];
                            [next addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside];
                            next.frame = image.frame;
                            //                            next.backgroundColor=luseColor;
                            [scroll2 addSubview:next];
                            
                            
                            UISwipeGestureRecognizer *swipeLeftGesture=[[UISwipeGestureRecognizer alloc]
                                                                        initWithTarget:self action:@selector(handleSwipeGesture:)];
                            
                            swipeLeftGesture.direction=UISwipeGestureRecognizerDirectionLeft;//右
                            
                            [next addGestureRecognizer:swipeLeftGesture];
                            
                            
                        }
                        
                        
                    }
                    
                }
                
                
                
                mainScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,1040*ScreenHeight/1334, ScreenWidth,ScreenHeight*280/1334)];
                mainScroll.delegate = self;
                mainScroll.userInteractionEnabled = YES;
                mainScroll.scrollEnabled = YES;
                mainScroll.showsVerticalScrollIndicator = FALSE;
                mainScroll.showsHorizontalScrollIndicator = FALSE;
                
                [self .view addSubview:mainScroll];
                commdity.Dict=severDataDict.dataDict;
                
                UILabel*title=[[UILabel alloc]initWithFrame:CGRectMake(20, 80*ScreenHeight/1334, ScreenWidth-40, 17)];
                title.textColor=[UIColor whiteColor];
                title.font=[UIFont boldSystemFontOfSize:17];
                 title.text=[NSString stringWithFormat:@"%@", [severDataDict.dataDict objectForKey:@"title"]];
//                title.text=[NSString stringWithFormat:@"%@ %@㎡ %@ ", [severDataDict.dataDict objectForKey:@"title"], [severDataDict.dataDict objectForKey:@"caseArea"], [severDataDict.dataDict objectForKey:@"caseHouse"]];
                [mainScroll addSubview:title];
                
                
                
                NSString *s12 = [NSString stringWithFormat:@"%@", [severDataDict.dataDict objectForKey:@"detail"]];
                UIFont *font12 = [UIFont systemFontOfSize:15];
                
                CGSize size12 = CGSizeMake(ScreenWidth-30, 2000);
                CGSize labelsize12 = [s12 sizeWithFont:font12 constrainedToSize:size12 lineBreakMode:NSLineBreakByCharWrapping];
                
                UILabel*details2=[[UILabel alloc]initWithFrame:CGRectMake(20, 150*ScreenHeight/1334, ScreenWidth-30, labelsize12.height)];
                details2.text=[NSString stringWithFormat:@"%@", [severDataDict.dataDict objectForKey:@"detail"]];
                details2.textColor=[UIColor whiteColor];
                details2.numberOfLines=0;
                details2.font=[UIFont systemFontOfSize:15];
                [mainScroll addSubview:details2];
                
                
                [mainScroll setContentSize:CGSizeMake(ScreenWidth, details2.bottom)];
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
  
    
}





-(NSString *) getImageFromURLs:(NSString *)imageUrl {
    
    
    
    NSString * results;
    
    
    [imageUrlarrays addObject:imageUrl];
    
    
    commdity.imageUrls=imageUrlarrays;
    return results;
    
}

-(UIImage *) getImageFromURL:(NSString *)fileURL {
    
    
    UIImage * result;

    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    
    result = [UIImage imageWithData:data];
    
    [imagearrays addObject:result];
   
    NSLog(@"aaaaaaaa%@",imagearrays);
    
    commdity.imageUrlFullarr1=imagearrays;
    return result;
    
}




-(void)closeKeyBoad
{
    [fengxiangview removeFromSuperview];
    [fengxiangScroll removeFromSuperview];
    [quxiao removeFromSuperview];
   
}
-(void)fenxiangss:(UIButton*)sender{
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"case" forKey:@"contentType"];
    [param setValue:commdity.caseID forKey:@"contentId"];
    [param setValue:@"wx_single" forKey:@"shareTarget"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"Company/getShareUrl" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                self.shuoming=[severDataDict.dataDict objectForKey:@"shareDescription"];
                self.shareUrl=[severDataDict.dataDict objectForKey:@"shareUrl"];
                
                fengxiangview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                fengxiangview.backgroundColor=[UIColor blackColor];
                fengxiangview.alpha=0.5;
                [self.view addSubview:fengxiangview];
                
                fengxiangScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,ScreenHeight-240, ScreenWidth,200)];
                fengxiangScroll.delegate = self;
                fengxiangScroll.userInteractionEnabled = YES;
                fengxiangScroll.scrollEnabled = YES;
                fengxiangScroll.showsVerticalScrollIndicator = FALSE;
                fengxiangScroll.showsHorizontalScrollIndicator = FALSE;
                fengxiangScroll.backgroundColor=[UIColor whiteColor];
                [self .view addSubview:fengxiangScroll];
                
                // 手势
                UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyBoad)];
                singleFingerOne.numberOfTouchesRequired = 1; //手指数
                singleFingerOne.numberOfTapsRequired = 1; //tap次数
                singleFingerOne.delegate = self;
                [fengxiangview addGestureRecognizer:singleFingerOne];
                
                
                
                
                NSArray*nameBtn=[[NSArray alloc]initWithObjects:@"发送給朋友",@"分享到朋友圈",nil];
                NSArray *arrayimage = @[@"faweixin",@"fenxiangpenyouquan"];
                for (int i = 0; i<2; i++) {
                    UIButton *nameButcenter = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/3*i,   80*ScreenHeight/1334+15, ScreenWidth/3, 60)];
                    
                    [fengxiangScroll addSubview:nameButcenter];
                    
                    
                    UIButton *nameBut = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth/3*i,   nameButcenter.bottom+20, ScreenWidth/3, 14)];
                    [nameBut setTitle: [nameBtn objectAtIndex:i]  forState:UIControlStateNormal];
                    nameBut.tag=201+i;
                    [nameBut setTitleColor:shenhuicolor forState:0];
                    nameBut.titleLabel.font=[UIFont systemFontOfSize:14];
                    [nameBut addTarget:self action:@selector(fengxiang:) forControlEvents:UIControlEventTouchUpInside];
                    [fengxiangScroll addSubview:nameBut];
                    
                    
                    UIButton *wuyebuttonimage = [UIButton buttonWithType:UIButtonTypeCustom];
                    wuyebuttonimage.frame = CGRectMake(ScreenWidth/3*i,  10, 60, 60);
                    
                    wuyebuttonimage.tag = 201+i;
                    wuyebuttonimage.center=nameButcenter.center;
                    [wuyebuttonimage setImage:[UIImage imageNamed: [arrayimage objectAtIndex:i]] forState:UIControlStateNormal];
                    [wuyebuttonimage addTarget:self action:@selector(fengxiang:) forControlEvents:UIControlEventTouchUpInside];
                    [fengxiangScroll addSubview:wuyebuttonimage];
                    
                    
                }
                
                
                quxiao = [[UIButton alloc] initWithFrame:CGRectMake(0,ScreenHeight-45,  ScreenWidth, 45)];
                [quxiao setTitle:@"取消" forState:UIControlStateNormal];
                quxiao.titleLabel.font=[UIFont systemFontOfSize:16];
                quxiao.backgroundColor=[UIColor whiteColor];
                [quxiao setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [quxiao addTarget:self action:@selector(closeKeyBoad) forControlEvents:UIControlEventTouchUpInside];
                [self .view addSubview:quxiao];
                UILabel*line=[[UILabel alloc]initWithFrame:CGRectMake(15, 0, ScreenWidth-30, 0.35)];
                line.backgroundColor=qianhuicolor;
                [quxiao addSubview:line];
                
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
    
    
    
}






-(void)fengxiang:(UIButton*)sender{
    [fengxiangview removeFromSuperview];
    [fengxiangScroll removeFromSuperview];
    [quxiao removeFromSuperview];
    NSURL *url = [NSURL URLWithString:[[[dataDicts valueForKey:@"imageList"] objectAtIndex:0]objectForKey:@"imageUrlFull"]];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image1 = [[UIImage alloc] initWithData:data];
    if (sender.tag==201) {
        if (![[commdity.Dict objectForKey:@"details"]isEqualToString:@""]) {
            self.shuoming=[commdity.Dict objectForKey:@"details"];
        }
        [UMSocialData defaultData].extConfig.wechatSessionData.title =[commdity.Dict objectForKey:@"itemName"];
        UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:self.shareUrl];
        
        [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatSession].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
        [UMSocialData defaultData].extConfig.wechatSessionData.url = self.shareUrl;
        [[UMSocialDataService defaultDataService]postSNSWithTypes:@[UMShareToWechatSession] content:self.shuoming image:image1 location:nil urlResource:urlResource presentedController:self completion:^(UMSocialResponseEntity *response){
            
            if (response.responseCode == UMSResponseCodeSuccess) {
                NSLog(@"分享成功！");
            }
            
        }];
        
        
        
        
        
        
    }
    
    if (sender.tag==202) {
        
        //         [UMSocialData defaultData].extConfig.wechatSessionData.title =[commdity.Dict objectForKey:@"itemName"];
        UMSocialUrlResource *urlResource = [[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:self.shareUrl];
        [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToWechatTimeline].snsClickHandler(self,[UMSocialControllerService defaultControllerService],YES);
        [UMSocialData defaultData].extConfig.wechatTimelineData.url = self.shareUrl;
        [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:[NSString stringWithFormat:@"%@",  [commdity.Dict objectForKey:@"itemName"]] image:image1 location:nil urlResource:urlResource presentedController:self completion:^(UMSocialResponseEntity *response){
            if (response.responseCode == UMSResponseCodeSuccess) {
                NSLog(@"分享成功！");
            }
        }];
        
        
        
        
    }
    
}


- (void)handleSwipeGesture:(UISwipeGestureRecognizer *)sender
{
    
    BusinessCaseItemListViewController* store=[[BusinessCaseItemListViewController alloc]init];
    
    [self.navigationController pushViewController:store animated:YES];

    
    }


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
   
    NSLog(@"%.f",scrollView.contentOffset.x*2);
    if (scrollView.contentOffset.x*2 > ScreenWidth* active.count+150) {
       scroll2.scrollEnabled = NO;
        commdity.gengxinxiangqing=@"";
        BusinessCaseItemListViewController* store=[[BusinessCaseItemListViewController alloc]init];
        
        [self.navigationController pushViewController:store animated:YES];
    
    
    }
    else {
        
        
        
//        scroll2.scrollEnabled = YES;
    }
}
-(void)handleSwipeGesture{
  
    BusinessCaseItemListViewController* store=[[BusinessCaseItemListViewController alloc]init];
    
    [self.navigationController pushViewController:store animated:YES];

    
}

- (void)start:(id)sender {
//    BusinessCaseItemListViewController* store=[[BusinessCaseItemListViewController alloc]init];
//    
//    [self.navigationController pushViewController:store animated:YES];
//
    
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
@end